package com.ice.delay.task.util;

import cn.hutool.core.exceptions.ExceptionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author wangwei
 * @Date 2023/11/14 18:30
 */
public class CommonUtil {
    private static final Logger logger = LoggerFactory.getLogger(CommonUtil.class);

    public static final long SECOND = 1 * 1000;
    public static final long MINUTE = 60 * SECOND;
    public static final long HOUR = 60 * MINUTE;
    public static final long DAY = 24 * HOUR;
    public static final long WEEK = 7 * DAY;

    /**
     * 执行Consumer并将异常化解在内部.
     */
    public static final <T> boolean exeConsumer(Consumer<T> c, T t) {
        try {
            c.accept(t);
            return true;
        } catch (Exception e) {
            logger.warn("t: {}, e: {}", t, ExceptionUtil.stacktraceToString(e));
            return false;
        }
    }

    /**
     * 执行Function并将异常化解在内部.
     */
    public static final <T, R> R exeFunction(Function<T, R> f, T t) {
        try {
            return f.apply(t);
        } catch (Exception e) {
            logger.warn("{}", ExceptionUtil.stacktraceToString(e));
            return null;
        }
    }


    /**
     * 判断为空的方法
     * @param object
     * @return
     */
    public static boolean isEmpty(Object object) {
        if (object == null) {
            return true;
        } else if (object instanceof String) {
            return "".equals(object.toString());
        } else if (object instanceof Collection) {
            return ((Collection)object).isEmpty();
        } else if (object instanceof Object[]) {
            return ((Object[])((Object[])object)).length == 0;
        } else if (object instanceof Map) {
            return ((Map)object).isEmpty();
        } else{
            return false;
        }
    }

    public static boolean isNotEmpty(Object object){
        return !isEmpty(object);
    }
}
